package com.gt.aep.base.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class EncryptUtil {

    /**
     * 对数据进行加密
     */
    public static Map<String, Object> encryptData(List l, String jsPublicKey){
        Map<String, Object> model = new HashedMap();
        //16位  AES的key
        String key = AesUtil.getKey();
        System.out.println("生成的AES--KEY："+key);

        try {
            //AES数据加密
            String encryptData = AesUtil.encrypt(l.toString(), key);
            //RSA前端公钥加密AES的明文key
//            byte[] sencryptKey = RsaUtil.encryptByPublicKey(key.getBytes(),jsPublicKey);
            String sencryptKey = Base64.encodeBase64String(RsaUtil.encryptByPublicKey(key.getBytes(), jsPublicKey));


            //解密
            String decryptDaa = AesUtil.decrypt(encryptData, key);

            model.put("l", l);
            model.put("encryptData", encryptData);
            model.put("decryptDaa", decryptDaa);
            model.put("sencryptKey", sencryptKey);
            model.put("javaKey", key);
            System.out.println("加密前：" + l);
            System.out.println("加密后：" + encryptData);
            System.out.println("解密后：" + decryptDaa);
            System.out.println("sencryptKey：" + sencryptKey);
            System.out.println("javaKey：" + key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return model;
    }

    /**
     * 对数据进行解密
     * @return
     */
    public static Map<String, Object> decode(String data, String encryptAesKey){
        //存放的解析出的 jsAesKey  和  data  数据
        Map<String, Object> model = new HashedMap();

        //解密前端发送过来的数据
        //使用后端的RSA私钥对前端的AES加密key进行解密
        String jsPublicKey = null;
        try {
            byte[] plaintext = RsaUtil.decryptByPrivateKey(Base64.decodeBase64(encryptAesKey),RsaUtil.getPrivateKey());
            String jsAesKey = new String(plaintext);
            System.out.println("私钥解密后的key："+jsAesKey);

            jsAesKey = jsAesKey.substring(1, jsAesKey.length() - 1);

            System.out.println("data:::"+data);
            System.out.println("jsAesKey:"+jsAesKey);
            //使用解密得到的后端AES明文key进行数据解密
            String decrypt = AesUtil.decrypt(data, jsAesKey);
            System.out.println("解密出来的data数据：" + decrypt);
            //将String类型数据转化为对象
            JSONObject dataObject = new JSONObject(JSONObject.parseObject(decrypt));
            jsPublicKey = (String) dataObject.get("jsPublicKey");
            model.put("jsAesKey",jsAesKey);
            model.put("data",decrypt);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return model;
    }
}
